package com.example.demo.api;


import com.example.demo.component.OnlineUserManage;
import com.example.demo.model.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.el.parser.AstFalse;
import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;


@Component
public class WebSocketAPI extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManage onlineUserManage;

    private ObjectMapper objectMapper=new ObjectMapper();
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接成功");
        User user=(User)session.getAttributes().get("user");
        if(user==null){
            return;
        }
        System.out.println("获取到的userId:"+user.getUserId());
        onlineUserManage.online(user.getUserId(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("接收到的消息是: "+message.toString());
//        1.先获取用户的信息
        User user=(User) session.getAttributes().get("user");
        if(user==null){
            return;
        }
//        2.针对请求进行解析
        MessageRequest request=objectMapper.readValue(message.getPayload(),MessageRequest.class);
        if(request.getType().equals("message")){
            transferMessage(user,request);
        }else{
            System.out.println("有误");
        }
    }

    private void transferMessage(User fromuser, MessageRequest request) throws IOException {
        MessageResponse resp=new MessageResponse();
        resp.setType("message");
        resp.setFromId(fromuser.getUserId());
        resp.setFromName(fromuser.getUsername());
        resp.setSessionId(request.getSessionId());
        resp.setContent(request.getContent());
        String respJson=objectMapper.writeValueAsString(resp);

      List<Friend> friends= messageSessionMapper.getFriendsBySessionId(request.getSessionId(),fromuser.getUserId());
      Friend myself=new Friend();
      myself.setFriendId(fromuser.getUserId());
      myself.setFriendName(fromuser.getUsername());
      friends.add(myself);


      for(Friend friend:friends){
         WebSocketSession webSocketSession= onlineUserManage.getSession(friend.getFriendId());
         if(webSocketSession==null){
             continue;
         }
         webSocketSession.sendMessage(new TextMessage(respJson));
      }
        Message message=new Message();
      message.setContent(request.getContent());
        message.setFromId(fromuser.getUserId());
        message.setSessionId(request.getSessionId());


        messageMapper.add(message);






    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常"+exception.toString());
        User user=(User) session.getAttributes().get("user");
        if(user==null){
            return;
        }
        onlineUserManage.offline(user.getUserId(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭"+status.toString());
        User user=(User) session.getAttributes().get("user");
        if(user==null){
            return;
        }
        onlineUserManage.offline(user.getUserId(),session);
    }
}
